import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
	// 为了完整类型推理，推荐使用箭头函数
	state: () => {
		return {
			productList: [],
			cartList: []
		}
	},
	getters: {
		count() {
			return this.cartList.length
		}
	},
	actions: {
		// 添加到购物车
		addCart(id) {
			// 先判断购物车是否已有，如果有，数量+1
			const isAdded = this.cartList.find(item => item.id === id);
			if (isAdded) {
				isAdded.count++;
			} else {
				this.cartList.push({
					id: id,
					count: 1
				})
			}
		},
		// 修改商品数量
		editCartCount(payload) {
			const product = this.cartList.find(item => item.id === payload.id);
			product.count += payload.count;
		},
		// 删除商品
		deleteCart(id) {
			const index = this.cartList.findIndex(item => item.id === id);
			this.cartList.splice(index, 1);
		},
		// 清空购物车
		emptyCart() {
			this.cartList = [];
		},
		// 购买
		async buy() {
			// 真实环境应通过 ajax 提交购买请求后再清空购物列表
			await new Promise(resolve => {
				setTimeout(() => {
					resolve();
				}, 1000)
			});
			this.emptyCart();
		}
	},
})